package com.media.controller;

import java.util.ArrayList;
import java.util.UUID;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.RedirectView;

import com.media.example.restapi.RESTSearchExample;
import com.media.model.SearchTweet;
import com.media.model.Tweet;
import com.media.service.TweetSearchService;
   
@Controller    
public class TweetSearchController {  
   
	
	@Autowired
	private TweetSearchService tweetService;
	
    @RequestMapping(value = "/tweetlist", method = RequestMethod.GET)  
	public String getTweetList(ModelMap model) {  
        model.addAttribute("tweetList", tweetService.listTweet());  
        return "tweetList";  
    }  
    
    @RequestMapping(value = "/tweet/search", method = RequestMethod.POST)  
	public View searchTweet(@ModelAttribute SearchTweet tweet, ModelMap model) {
    	JSONArray res=RESTSearchExample.getSearchResults(tweet.getSearch());
    	ArrayList<Tweet> listp=new ArrayList<Tweet>();
    	for(int i=1;i<res.length();i++)
    	{
    		Tweet ts= new Tweet();
    		ts.setId(UUID.randomUUID().toString());
    		JSONObject obj=res.getJSONObject(i);
    		ts.setText(obj.get("text").toString());
    		listp.add(ts);
    		
    	}
    	tweetService.updateTweetALL(listp);
    	return new RedirectView("/tweetlist", true); 
    }
        
    @RequestMapping(value = "/tweet/delete", method = RequestMethod.GET)  
	public View deleteTweet(@ModelAttribute Tweet tweet, ModelMap model) {  
        tweetService.deleteTweet(tweet);  
        return new RedirectView("/tweetlist", true);  
    }    
}
